<template>
  <div class="com-dialog">
    <el-dialog
      :visible.sync="show"
      :width="option.width || '60%'"
      :destroy-on-close="true"
      :fullscreen="fullscreen"
      @close="closeDialogHandler"
    >
      <template slot="title">
        <div class="dialog-title-box">
          <span class="title">{{ titleData[option.type] }}</span>
          <span class="fullscreen" @click="fullscreen = !fullscreen"
            ><i class="el-icon-full-screen"></i
          ></span>
        </div>
      </template>
      <slot />
      <!-- footer 插槽可以自定义按钮 -->
      <div slot="footer" class="dialog-footer" v-if="option.type != 'view'">
        <el-button
          v-if="isShow(option.submitBtn)"
          :size="option.size || 'small'"
          :loading="loading"
          :type="option.submitBtnType || 'primary'"
          @click="submit"
          >{{ submitBtnText }}</el-button
        >
        <el-button
          v-if="isShow(option.cancelBtn)"
          :size="option.size || 'small'"
          :disabled="loading"
          :type="option.cancelBtnType || ''"
          @click="closeDialogHandler"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ComDialog",
  props: {
    visible: {
      type: Boolean,
      default: () => false,
    },
    option: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      show: false,
      loading: false, // 按钮加载动画
      fullscreen: false, // 是否全屏
      titleData: {
        add: "添加",
        edit: "编辑",
        view: "查看",
      },
    };
  },
  watch: {
    show: function (newVal) {
      this.$emit("update:visible", newVal);
    },
    visible: function (newVal) {
      this.show = newVal;
    },
  },
  computed: {
    submitBtnText() {
      if (this.loading) return "提交中";
      return this.option.type === "add" ? "提交" : "修改";
    },
  },
  methods: {
    isShow(e) {
      return e === false ? false : true;
    },
    /** 关闭dialog */
    closeDialogHandler() {
      this.loading = false;
      this.show = false;
      this.$emit("on-close");
    },

    /** 确定按钮触发 */
    submit() {
      this.onLoading();
      this.$emit(
        "on-submit",
        () => {
          this.closeDialogHandler();
        },
        () => {
          this.endLoading();
        }
      );
    },

    /** 加载时确定按钮文字和状态 */
    onLoading() {
      this.loading = true;
    },

    /** 完成加载后得确认按钮文字和状态 */
    endLoading() {
      this.loading = false;
    },
  },
};
</script>

<style scoped lang="less">
.dialog-title-box {
  line-height: 24px;
  font-size: 18px;
  color: #303133;
  display: flex;
  justify-content: space-between;

  .fullscreen {
    transform: translate(-30px, -4px);
    cursor: pointer;
    :hover {
      color: #409eff;
    }
  }
}

.dialog-footer {
  text-align: center;
}
</style>
